import { readdirSync, statSync } from "node:fs"
import path from "node:path"

/** 格式化字节单位 */
export function formatBytes(bytes: number, decimals: number = 3): string {
    const units: string[] = ['B', 'KB', 'MB', 'GB']
    let unitIndex: number = 0
    while (bytes >= 1024 && unitIndex < units.length -1) {
        bytes /= 1024
        unitIndex++
    }
    return `${bytes.toFixed(decimals)} ${units[unitIndex]}`
}


/** 获取指定文件夹中所有文件的总大小 */
export const getDirectorySize = (dirPath: string) => {
    let totalSize = 0
    const traverse = (currentPath:string) => {
        const items = readdirSync(currentPath)
        for(const item of items) {
            const fullPath = path.join(currentPath, item)
            const stats = statSync(fullPath)
            if (stats.isDirectory()) {
                traverse(fullPath)
            } else if (stats.isFile()) {
                totalSize += stats.size
            }
        }
    }
    traverse(dirPath)
    return totalSize
}
